package cn.wolfcode.ssm.web.controller;


import cn.wolfcode.ssm.domain.Activity;
import cn.wolfcode.ssm.domain.ActivityItem;
import cn.wolfcode.ssm.service.IActivityService;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.qo.JsonResult;
import cn.wolfcode.ssm.util.RequireAnnotation;
import cn.wolfcode.ssm.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private IActivityService activityService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Activity> pageInfo = activityService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "activity/投票列表";
    }


    @RequestMapping("/input")
    public String input(Model model,Long id){
        Activity activity = activityService.get(id);
        model.addAttribute("activity", activity);
        return "activity/投票页面";
    }




    @RequestMapping("/save")
    @ResponseBody
    public JsonResult save(Activity activity,Long activityItemId){
        Long employeeId = UserContext.getEmployee().getId();
        List<Long> employeeIds = activityService.selectChoiceByActivityId(activity.getId());
        if (employeeIds.contains(employeeId)){
            return new JsonResult(false,"你已经投过票");
        }
        Long id = activityService.save(activity, activityItemId);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(id);
        return jsonResult;
    }

    @RequestMapping("/result")
    public String result(Model model,Long id){
        Activity activity = activityService.get(id);
        int totalNum = 0;
        List<ActivityItem> activityItems = activity.getActivityItems();
        for (int i = 0; i < activityItems.size(); i++) {
            totalNum += activityItems.get(i).getNum();
        }
        model.addAttribute("activity", activity);
        model.addAttribute("totalNum", totalNum);
        return "activity/投票结果";
    }

}
